import 'package:flutter/foundation.dart';

// 社区帖子模型
class CommunityPost {
  final String id;
  final String title;
  final String content;
  final String authorId;
  final String authorName;
  final String authorAvatar;
  final DateTime createdAt;
  final DateTime updatedAt;
  final String category;
  final List<String> tags;
  final List<String> imageUrls;
  final int likeCount;
  final int commentCount;
  final int viewCount;
  final bool isPinned;
  final bool isHot;
  final PostStatus status;

  const CommunityPost({
    required this.id,
    required this.title,
    required this.content,
    required this.authorId,
    required this.authorName,
    required this.authorAvatar,
    required this.createdAt,
    required this.updatedAt,
    required this.category,
    required this.tags,
    required this.imageUrls,
    required this.likeCount,
    required this.commentCount,
    required this.viewCount,
    required this.isPinned,
    required this.isHot,
    required this.status,
  });

  CommunityPost copyWith({
    String? id,
    String? title,
    String? content,
    String? authorId,
    String? authorName,
    String? authorAvatar,
    DateTime? createdAt,
    DateTime? updatedAt,
    String? category,
    List<String>? tags,
    List<String>? imageUrls,
    int? likeCount,
    int? commentCount,
    int? viewCount,
    bool? isPinned,
    bool? isHot,
    PostStatus? status,
  }) {
    return CommunityPost(
      id: id ?? this.id,
      title: title ?? this.title,
      content: content ?? this.content,
      authorId: authorId ?? this.authorId,
      authorName: authorName ?? this.authorName,
      authorAvatar: authorAvatar ?? this.authorAvatar,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      category: category ?? this.category,
      tags: tags ?? this.tags,
      imageUrls: imageUrls ?? this.imageUrls,
      likeCount: likeCount ?? this.likeCount,
      commentCount: commentCount ?? this.commentCount,
      viewCount: viewCount ?? this.viewCount,
      isPinned: isPinned ?? this.isPinned,
      isHot: isHot ?? this.isHot,
      status: status ?? this.status,
    );
  }
}

// 评论模型
class Comment {
  final String id;
  final String postId;
  final String content;
  final String authorId;
  final String authorName;
  final String authorAvatar;
  final DateTime createdAt;
  final int likeCount;
  final String? parentId; // 用于回复评论
  final List<Comment> replies;

  const Comment({
    required this.id,
    required this.postId,
    required this.content,
    required this.authorId,
    required this.authorName,
    required this.authorAvatar,
    required this.createdAt,
    required this.likeCount,
    this.parentId,
    required this.replies,
  });

  Comment copyWith({
    String? id,
    String? postId,
    String? content,
    String? authorId,
    String? authorName,
    String? authorAvatar,
    DateTime? createdAt,
    int? likeCount,
    String? parentId,
    List<Comment>? replies,
  }) {
    return Comment(
      id: id ?? this.id,
      postId: postId ?? this.postId,
      content: content ?? this.content,
      authorId: authorId ?? this.authorId,
      authorName: authorName ?? this.authorName,
      authorAvatar: authorAvatar ?? this.authorAvatar,
      createdAt: createdAt ?? this.createdAt,
      likeCount: likeCount ?? this.likeCount,
      parentId: parentId ?? this.parentId,
      replies: replies ?? this.replies,
    );
  }
}

// 用户资料模型
class UserProfile {
  final String id;
  final String username;
  final String displayName;
  final String avatar;
  final String bio;
  final DateTime joinDate;
  final int postCount;
  final int followerCount;
  final int followingCount;
  final int likeCount;
  final List<String> badges;
  final Map<String, dynamic> stats;
  final UserLevel level;

  const UserProfile({
    required this.id,
    required this.username,
    required this.displayName,
    required this.avatar,
    required this.bio,
    required this.joinDate,
    required this.postCount,
    required this.followerCount,
    required this.followingCount,
    required this.likeCount,
    required this.badges,
    required this.stats,
    required this.level,
  });

  UserProfile copyWith({
    String? id,
    String? username,
    String? displayName,
    String? avatar,
    String? bio,
    DateTime? joinDate,
    int? postCount,
    int? followerCount,
    int? followingCount,
    int? likeCount,
    List<String>? badges,
    Map<String, dynamic>? stats,
    UserLevel? level,
  }) {
    return UserProfile(
      id: id ?? this.id,
      username: username ?? this.username,
      displayName: displayName ?? this.displayName,
      avatar: avatar ?? this.avatar,
      bio: bio ?? this.bio,
      joinDate: joinDate ?? this.joinDate,
      postCount: postCount ?? this.postCount,
      followerCount: followerCount ?? this.followerCount,
      followingCount: followingCount ?? this.followingCount,
      likeCount: likeCount ?? this.likeCount,
      badges: badges ?? this.badges,
      stats: stats ?? this.stats,
      level: level ?? this.level,
    );
  }
}

// 枚举定义
enum PostStatus { published, draft, hidden, deleted }
enum UserLevel { newbie, bronze, silver, gold, platinum, diamond }
enum SortType { latest, hot, popular, oldest }

// 社区状态管理
class CommunityProvider with ChangeNotifier {
  List<CommunityPost> _posts = [];
  List<CommunityPost> _filteredPosts = [];
  List<Comment> _comments = [];
  List<UserProfile> _users = [];
  
  String _selectedCategory = 'all';
  SortType _sortType = SortType.latest;
  String _searchQuery = '';
  bool _isLoading = false;
  String? _error;
  
  // 用户交互数据
  final Set<String> _likedPosts = {};
  final Set<String> _likedComments = {};
  final Set<String> _followedUsers = {};
  final Map<String, List<Comment>> _postComments = {};
  
  // 当前用户信息
  UserProfile? _currentUser;

  // Getters
  List<CommunityPost> get posts => _posts;
  List<CommunityPost> get filteredPosts => _filteredPosts;
  List<Comment> get comments => _comments;
  List<UserProfile> get users => _users;
  String get selectedCategory => _selectedCategory;
  SortType get sortType => _sortType;
  String get searchQuery => _searchQuery;
  bool get isLoading => _isLoading;
  String? get error => _error;
  Set<String> get likedPosts => _likedPosts;
  Set<String> get likedComments => _likedComments;
  Set<String> get followedUsers => _followedUsers;
  UserProfile? get currentUser => _currentUser;

  CommunityProvider() {
    _loadInitialData();
  }

  void _loadInitialData() {
    _isLoading = true;
    notifyListeners();

    // 模拟加载数据
    Future.delayed(const Duration(milliseconds: 800), () {
      _users = _generateMockUsers();
      _posts = _generateMockPosts();
      _comments = _generateMockComments();
      _currentUser = _users.first; // 模拟当前用户
      _filteredPosts = List.from(_posts);
      _loadUserInteractionData();
      _applySortAndFilter();
      _isLoading = false;
      notifyListeners();
    });
  }

  List<UserProfile> _generateMockUsers() {
    return [
      UserProfile(
        id: 'user_1',
        username: 'heritage_lover',
        displayName: '文化传承者',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20culture%20enthusiast%20portrait&image_size=square',
        bio: '热爱传统文化，致力于非遗技艺的学习与传承',
        joinDate: DateTime.now().subtract(const Duration(days: 365)),
        postCount: 45,
        followerCount: 1200,
        followingCount: 300,
        likeCount: 2800,
        badges: ['文化达人', '活跃用户', '优质内容创作者'],
        stats: {
          'totalViews': 15000,
          'totalLikes': 2800,
          'bestPost': 'post_1',
        },
        level: UserLevel.gold,
      ),
      UserProfile(
        id: 'user_2',
        username: 'calligraphy_master',
        displayName: '墨香书韵',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20calligraphy%20artist%20portrait&image_size=square',
        bio: '书法爱好者，分享书法学习心得与作品',
        joinDate: DateTime.now().subtract(const Duration(days: 200)),
        postCount: 32,
        followerCount: 890,
        followingCount: 150,
        likeCount: 1950,
        badges: ['书法专家', '内容贡献者'],
        stats: {
          'totalViews': 8500,
          'totalLikes': 1950,
          'bestPost': 'post_2',
        },
        level: UserLevel.silver,
      ),
      UserProfile(
        id: 'user_3',
        username: 'tea_ceremony',
        displayName: '茶香悠然',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20tea%20ceremony%20master%20portrait&image_size=square',
        bio: '茶艺师，分享茶文化知识与品茶心得',
        joinDate: DateTime.now().subtract(const Duration(days: 120)),
        postCount: 28,
        followerCount: 650,
        followingCount: 200,
        likeCount: 1400,
        badges: ['茶艺专家', '新人导师'],
        stats: {
          'totalViews': 6200,
          'totalLikes': 1400,
          'bestPost': 'post_3',
        },
        level: UserLevel.bronze,
      ),
    ];
  }

  List<CommunityPost> _generateMockPosts() {
    return [
      CommunityPost(
        id: 'post_1',
        title: '我的书法学习之路：从零基础到小有所成',
        content: '分享我这一年来学习书法的心得体会。刚开始握笔都不会，现在已经能写出像样的楷书了。最重要的是要坚持每天练习，还要找到好的老师指导...',
        authorId: 'user_1',
        authorName: '文化传承者',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20culture%20enthusiast%20portrait&image_size=square',
        createdAt: DateTime.now().subtract(const Duration(hours: 2)),
        updatedAt: DateTime.now().subtract(const Duration(hours: 2)),
        category: 'experience',
        tags: ['书法', '学习心得', '初学者'],
        imageUrls: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20calligraphy%20practice%20work&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=calligraphy%20tools%20and%20materials&image_size=landscape_4_3',
        ],
        likeCount: 156,
        commentCount: 23,
        viewCount: 890,
        isPinned: false,
        isHot: true,
        status: PostStatus.published,
      ),
      CommunityPost(
        id: 'post_2',
        title: '传统茶艺表演技巧分享',
        content: '茶艺表演不仅是技艺的展示，更是文化的传承。今天分享几个茶艺表演的关键技巧：手法要优雅、动作要连贯、心境要平和...',
        authorId: 'user_3',
        authorName: '茶香悠然',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20tea%20ceremony%20master%20portrait&image_size=square',
        createdAt: DateTime.now().subtract(const Duration(hours: 5)),
        updatedAt: DateTime.now().subtract(const Duration(hours: 5)),
        category: 'tutorial',
        tags: ['茶艺', '表演技巧', '文化传承'],
        imageUrls: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20tea%20ceremony%20performance&image_size=landscape_4_3',
        ],
        likeCount: 89,
        commentCount: 15,
        viewCount: 456,
        isPinned: true,
        isHot: false,
        status: PostStatus.published,
      ),
      CommunityPost(
        id: 'post_3',
        title: '古琴初学者常见问题解答',
        content: '很多朋友在学习古琴时会遇到各种问题，我整理了一些常见的问题和解答，希望对大家有帮助。1. 如何选择合适的古琴？2. 初学者应该从哪些曲目开始？...',
        authorId: 'user_2',
        authorName: '墨香书韵',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20calligraphy%20artist%20portrait&image_size=square',
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
        updatedAt: DateTime.now().subtract(const Duration(days: 1)),
        category: 'qa',
        tags: ['古琴', '初学者', '问题解答'],
        imageUrls: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20guqin%20instrument&image_size=landscape_4_3',
        ],
        likeCount: 67,
        commentCount: 12,
        viewCount: 234,
        isPinned: false,
        isHot: false,
        status: PostStatus.published,
      ),
      CommunityPost(
        id: 'post_4',
        title: '剪纸艺术创作分享：春节主题作品',
        content: '春节快到了，分享一些我最近创作的春节主题剪纸作品。包括福字、生肖、花卉等传统图案，每一幅都蕴含着美好的寓意...',
        authorId: 'user_1',
        authorName: '文化传承者',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20culture%20enthusiast%20portrait&image_size=square',
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
        updatedAt: DateTime.now().subtract(const Duration(days: 2)),
        category: 'showcase',
        tags: ['剪纸', '春节', '传统艺术'],
        imageUrls: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20paper%20cutting%20spring%20festival%20art&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20zodiac%20paper%20cutting&image_size=landscape_4_3',
        ],
        likeCount: 134,
        commentCount: 18,
        viewCount: 567,
        isPinned: false,
        isHot: true,
        status: PostStatus.published,
      ),
      CommunityPost(
        id: 'post_5',
        title: '国画山水技法讨论：如何表现云雾缭绕的效果',
        content: '在山水画中，云雾的表现是一个重要技法。今天想和大家讨论一下如何用不同的笔法和墨色来表现云雾缭绕的意境...',
        authorId: 'user_2',
        authorName: '墨香书韵',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20calligraphy%20artist%20portrait&image_size=square',
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
        updatedAt: DateTime.now().subtract(const Duration(days: 3)),
        category: 'discussion',
        tags: ['国画', '山水', '技法讨论'],
        imageUrls: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20landscape%20painting%20with%20clouds&image_size=landscape_4_3',
        ],
        likeCount: 45,
        commentCount: 8,
        viewCount: 189,
        isPinned: false,
        isHot: false,
        status: PostStatus.published,
      ),
    ];
  }

  List<Comment> _generateMockComments() {
    return [
      Comment(
        id: 'comment_1',
        postId: 'post_1',
        content: '写得真好！我也是书法初学者，很受启发。请问你是怎么选择字帖的？',
        authorId: 'user_2',
        authorName: '墨香书韵',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20calligraphy%20artist%20portrait&image_size=square',
        createdAt: DateTime.now().subtract(const Duration(hours: 1)),
        likeCount: 12,
        parentId: null,
        replies: [],
      ),
      Comment(
        id: 'comment_2',
        postId: 'post_1',
        content: '我建议从颜真卿的《多宝塔碑》开始，结构比较规整，适合初学者。',
        authorId: 'user_1',
        authorName: '文化传承者',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20culture%20enthusiast%20portrait&image_size=square',
        createdAt: DateTime.now().subtract(const Duration(minutes: 45)),
        likeCount: 8,
        parentId: 'comment_1',
        replies: [],
      ),
      Comment(
        id: 'comment_3',
        postId: 'post_2',
        content: '茶艺表演确实需要多练习，手法的优雅程度直接影响观感。',
        authorId: 'user_1',
        authorName: '文化传承者',
        authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20culture%20enthusiast%20portrait&image_size=square',
        createdAt: DateTime.now().subtract(const Duration(hours: 3)),
        likeCount: 5,
        parentId: null,
        replies: [],
      ),
    ];
  }

  void _loadUserInteractionData() {
    // 模拟加载用户交互数据
    _likedPosts.addAll(['post_1', 'post_4']);
    _likedComments.addAll(['comment_1', 'comment_3']);
    _followedUsers.addAll(['user_2', 'user_3']);
    
    // 组织评论数据
    for (final comment in _comments) {
      if (!_postComments.containsKey(comment.postId)) {
        _postComments[comment.postId] = [];
      }
      _postComments[comment.postId]!.add(comment);
    }
  }

  // 搜索和筛选
  void setSearchQuery(String query) {
    _searchQuery = query;
    _applySortAndFilter();
  }

  void setCategory(String category) {
    _selectedCategory = category;
    _applySortAndFilter();
  }

  void setSortType(SortType sortType) {
    _sortType = sortType;
    _applySortAndFilter();
  }

  void _applySortAndFilter() {
    // 筛选
    _filteredPosts = _posts.where((post) {
      final matchesCategory = _selectedCategory == 'all' || post.category == _selectedCategory;
      final matchesSearch = _searchQuery.isEmpty ||
          post.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          post.content.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          post.tags.any((tag) => tag.toLowerCase().contains(_searchQuery.toLowerCase()));
      return matchesCategory && matchesSearch;
    }).toList();

    // 排序
    switch (_sortType) {
      case SortType.latest:
        _filteredPosts.sort((a, b) => b.createdAt.compareTo(a.createdAt));
        break;
      case SortType.hot:
        _filteredPosts.sort((a, b) {
          final aScore = a.likeCount * 2 + a.commentCount * 3 + a.viewCount;
          final bScore = b.likeCount * 2 + b.commentCount * 3 + b.viewCount;
          return bScore.compareTo(aScore);
        });
        break;
      case SortType.popular:
        _filteredPosts.sort((a, b) => b.likeCount.compareTo(a.likeCount));
        break;
      case SortType.oldest:
        _filteredPosts.sort((a, b) => a.createdAt.compareTo(b.createdAt));
        break;
    }

    // 置顶帖子排在前面
    _filteredPosts.sort((a, b) {
      if (a.isPinned && !b.isPinned) return -1;
      if (!a.isPinned && b.isPinned) return 1;
      return 0;
    });

    notifyListeners();
  }

  // 帖子操作
  Future<bool> createPost({
    required String title,
    required String content,
    required String category,
    required List<String> tags,
    List<String>? imageUrls,
  }) async {
    try {
      _isLoading = true;
      notifyListeners();

      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 1));

      final newPost = CommunityPost(
        id: 'post_${DateTime.now().millisecondsSinceEpoch}',
        title: title,
        content: content,
        authorId: _currentUser!.id,
        authorName: _currentUser!.displayName,
        authorAvatar: _currentUser!.avatar,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        category: category,
        tags: tags,
        imageUrls: imageUrls ?? [],
        likeCount: 0,
        commentCount: 0,
        viewCount: 0,
        isPinned: false,
        isHot: false,
        status: PostStatus.published,
      );

      _posts.insert(0, newPost);
      _applySortAndFilter();
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = '发布失败: $e';
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  Future<bool> likePost(String postId) async {
    try {
      final postIndex = _posts.indexWhere((p) => p.id == postId);
      if (postIndex == -1) return false;

      final post = _posts[postIndex];
      final isLiked = _likedPosts.contains(postId);
      
      if (isLiked) {
        _likedPosts.remove(postId);
        _posts[postIndex] = post.copyWith(likeCount: post.likeCount - 1);
      } else {
        _likedPosts.add(postId);
        _posts[postIndex] = post.copyWith(likeCount: post.likeCount + 1);
      }
      
      _applySortAndFilter();
      return true;
    } catch (e) {
      _error = '操作失败: $e';
      notifyListeners();
      return false;
    }
  }

  Future<bool> addComment({
    required String postId,
    required String content,
    String? parentId,
  }) async {
    try {
      _isLoading = true;
      notifyListeners();

      // 模拟网络请求
      await Future.delayed(const Duration(milliseconds: 500));

      final newComment = Comment(
        id: 'comment_${DateTime.now().millisecondsSinceEpoch}',
        postId: postId,
        content: content,
        authorId: _currentUser!.id,
        authorName: _currentUser!.displayName,
        authorAvatar: _currentUser!.avatar,
        createdAt: DateTime.now(),
        likeCount: 0,
        parentId: parentId,
        replies: [],
      );

      _comments.add(newComment);
      
      // 更新帖子评论数
      final postIndex = _posts.indexWhere((p) => p.id == postId);
      if (postIndex != -1) {
        final post = _posts[postIndex];
        _posts[postIndex] = post.copyWith(commentCount: post.commentCount + 1);
      }
      
      // 更新评论组织
      if (!_postComments.containsKey(postId)) {
        _postComments[postId] = [];
      }
      _postComments[postId]!.add(newComment);
      
      _applySortAndFilter();
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = '评论失败: $e';
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  Future<bool> likeComment(String commentId) async {
    try {
      final commentIndex = _comments.indexWhere((c) => c.id == commentId);
      if (commentIndex == -1) return false;

      final comment = _comments[commentIndex];
      final isLiked = _likedComments.contains(commentId);
      
      if (isLiked) {
        _likedComments.remove(commentId);
        _comments[commentIndex] = comment.copyWith(likeCount: comment.likeCount - 1);
      } else {
        _likedComments.add(commentId);
        _comments[commentIndex] = comment.copyWith(likeCount: comment.likeCount + 1);
      }
      
      notifyListeners();
      return true;
    } catch (e) {
      _error = '操作失败: $e';
      notifyListeners();
      return false;
    }
  }

  Future<bool> followUser(String userId) async {
    try {
      if (_followedUsers.contains(userId)) {
        _followedUsers.remove(userId);
      } else {
        _followedUsers.add(userId);
      }
      notifyListeners();
      return true;
    } catch (e) {
      _error = '操作失败: $e';
      notifyListeners();
      return false;
    }
  }

  // 查询方法
  CommunityPost? getPostById(String id) {
    try {
      return _posts.firstWhere((post) => post.id == id);
    } catch (e) {
      return null;
    }
  }

  UserProfile? getUserById(String id) {
    try {
      return _users.firstWhere((user) => user.id == id);
    } catch (e) {
      return null;
    }
  }

  List<Comment> getPostComments(String postId) {
    return _postComments[postId] ?? [];
  }

  bool isPostLiked(String postId) {
    return _likedPosts.contains(postId);
  }

  bool isCommentLiked(String commentId) {
    return _likedComments.contains(commentId);
  }

  bool isUserFollowed(String userId) {
    return _followedUsers.contains(userId);
  }

  // 获取分类列表
  List<String> getCategories() {
    final categories = _posts.map((p) => p.category).toSet().toList();
    categories.sort();
    return ['all', ...categories];
  }

  // 获取热门标签
  List<String> getPopularTags({int limit = 10}) {
    final tagCounts = <String, int>{};
    for (final post in _posts) {
      for (final tag in post.tags) {
        tagCounts[tag] = (tagCounts[tag] ?? 0) + 1;
      }
    }
    
    final sortedTags = tagCounts.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));
    
    return sortedTags.take(limit).map((e) => e.key).toList();
  }

  // 获取用户统计
  Map<String, dynamic> getUserStats(String userId) {
    final userPosts = _posts.where((p) => p.authorId == userId).toList();
    final totalLikes = userPosts.fold(0, (sum, post) => sum + post.likeCount);
    final totalViews = userPosts.fold(0, (sum, post) => sum + post.viewCount);
    final totalComments = userPosts.fold(0, (sum, post) => sum + post.commentCount);
    
    return {
      'postCount': userPosts.length,
      'totalLikes': totalLikes,
      'totalViews': totalViews,
      'totalComments': totalComments,
      'averageLikes': userPosts.isNotEmpty ? totalLikes / userPosts.length : 0,
    };
  }

  // 获取推荐帖子
  List<CommunityPost> getRecommendedPosts({int limit = 5}) {
    // 基于用户喜欢的帖子推荐相似内容
    final likedCategories = <String>{};
    final likedTags = <String>{};
    
    for (final postId in _likedPosts) {
      final post = getPostById(postId);
      if (post != null) {
        likedCategories.add(post.category);
        likedTags.addAll(post.tags);
      }
    }
    
    final recommended = _posts.where((post) {
      if (_likedPosts.contains(post.id)) return false;
      return likedCategories.contains(post.category) ||
             post.tags.any((tag) => likedTags.contains(tag));
    }).toList();
    
    // 按热度排序
    recommended.sort((a, b) {
      final aScore = a.likeCount * 2 + a.commentCount * 3 + a.viewCount;
      final bScore = b.likeCount * 2 + b.commentCount * 3 + b.viewCount;
      return bScore.compareTo(aScore);
    });
    
    return recommended.take(limit).toList();
  }

  // 刷新数据
  Future<void> refresh() async {
    _error = null;
    _loadInitialData();
  }

  // 清除错误
  void clearError() {
    _error = null;
    notifyListeners();
  }
}